package com.example.asockets;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import com.google.gson.Gson;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements ActionBar.OnNavigationListener {

    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    TextView lbl1 = null;
    String serverIP = null;
    EditText enterIP = null;
    
    private GLSurfaceView mGLView;

    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button b1 = (Button)findViewById(R.id.button1);
        lbl1 = (TextView)findViewById(R.id.textView1);
        enterIP = (EditText)findViewById(R.id.editText1);
        
        Button change = (Button)findViewById(R.id.button2);
        
        mGLView = new MyGLSurfaceView(this);
	    
        
        b1.setOnClickListener(new View.OnClickListener() {
			
			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				
				serverIP = enterIP.getText().toString();
				
				//new network2().execute();
				lbl1.setText("network button clicked");
				//lbl1.setText("waste");
				new network4().execute();
				//lbl1.setText(enterIP.getText());
				
			}
		});//B1 LISTENER END

        change.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				//setContentView(R.layout.twoactivity);
				
				setContentView(mGLView);
				
				
				
			}
		});
        
        
        
        
        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
                // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter(
                        actionBar.getThemedContext(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1,
                        new String[]{
                                getString(R.string.title_section1),
                                getString(R.string.title_section2),
                                getString(R.string.title_section3),
                        }),
                this);
        
        
        
    }
    
    
    

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
                getActionBar().getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    protected void onProgressUpdate(Long... progress) {
        //Update UI
    	lbl1.setText("ok");
    }

    

    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        // When the given tab is selected, show the tab contents in the container
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, fragment)
                .commit();
        
        
        return true;
    }

    /**
     * A dummy fragment representing a section of the app, but that simply displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        public DummySectionFragment() {
        }

        public static final String ARG_SECTION_NUMBER = "section_number";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            TextView textView = new TextView(getActivity());
            textView.setGravity(Gravity.CENTER);
            Bundle args = getArguments();
            textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
            return textView;
        }
    }
    
    
    class network4 extends AsyncTask<Object, Integer, Object>{
    	
    	public Socket socket = null;
    	public  ObjectOutputStream objectOutputStream = null;
    	public  ObjectInputStream objectInputStream = null;
    	
    	//String serverIP = "192.168.0.101";
    	int port = 4444;
    	
    	Gson gson = new Gson();	
    	

	public network4(){}
    		
    		
	protected Object doInBackground(Object... params) {
		
		/**
		 *UI calls will NOT work within try/catch
		 *RESTUCTURE THIS
		 */
		
		lbl1.setText("network 4 successful");
		
		
		try {
			
					
			msg msgMessage = new msg("android device connected");
			String json = gson.toJson(msgMessage);
			
			
			
			
			String msgSend = "android connected";
			
			if(socket == null) {
				socket = new Socket(serverIP, 4444);
				//socket = new Socket("192.168.0.101", 4444);
				objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
				objectInputStream = new ObjectInputStream(socket.getInputStream());
				Log.v("NITESH", "connection established");
				
				
				
			}
			objectOutputStream.writeObject(json);
			//objectOutputStream.writeObject(msgSend);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		while (objectInputStream != null) {
			
			msg message = null;
        	//msg sendMsg = new msg("hello client");
        	
			String str = null;
        	
        	try {
        		
        		
        		//lbl1.setText("network 4 successful");
        		
        		str = (String) objectInputStream.readObject();
        		
        		lbl1.setText(str);
        		
        		
        		Log.v("NITESH", str + "network 4 call");
        		
        		
        	}
        	
        	catch(Exception e){
        		
        		
        	}
			
			
			
		}
		
//		try {
//			socket.close();
//			objectOutputStream.close();
//			objectInputStream.close();
//			socket = null;
//			objectInputStream = null;
//			objectOutputStream = null;
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		// TODO Auto-generated method stub
		return null;
	}

	protected void onProgressUpdate(Integer... progress) {
        
    }

    protected void onPostExecute(Long result) {
        
    }

    
    }
    
    
    
    class network3 extends AsyncTask<String, Integer, String>{
    	
     	public Socket socket = null;
    	public  ObjectOutputStream objectOutputStream = null;
    	public  ObjectInputStream objectInputStream = null;
    	
    	String serverIP = "192.168.0.101";
    	int port = 4444;
    	
    	Gson gson = new Gson();	
    	
    	
    	public network3(){
    		
    		//lbl1.setText("inner class working");
    		
    	}

		protected String doInBackground(String... params) {
			
			
			
			
			
			// TODO Auto-generated method stub
			lbl1.setText("do in background working");
			
			
			Log.v("NITESH", "network3 doInBackground working");
			
			
			return "bruce wayne";
		}
    	
		   protected void onPostExecute(int x) {
			   
			   Log.v("NITESH", "network3 doInBackground working");
			   
			   lbl1.setText("post exec  working");
		    }
    	
    }
    
    }




class network2 extends AsyncTask {
	
	
	public static Socket socket = null;
	public static ObjectOutputStream objectOutputStream = null;
	public static ObjectInputStream objectInputStream = null;
	
	String serverIP = "192.168.0.101";
	int port = 4444;
	
	Gson gson = new Gson();	
	
	  
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	public network2(){
		
		
		
		/*
		
	    try {
	    	socket = new Socket("192.168.0.106", 4444);
           // out = new PrintWriter(socket.getOutputStream(), true);
           // in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: taranis.");
            System.exit(1);
        }
		*/
		
	}
	

	@Override
	protected Object doInBackground(Object... params) {
		try {
			
					
			msg msgMessage = new msg("android device connected");
			String json = gson.toJson(msgMessage);
			
			
			
			
			String msgSend = "android connected";
			
			if(socket == null) {
				socket = new Socket("192.168.0.101", 4444);
				objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
				objectInputStream = new ObjectInputStream(socket.getInputStream());
				Log.v("NITESH", "connection established");
				
				
				
			}
			objectOutputStream.writeObject(json);
			//objectOutputStream.writeObject(msgSend);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		while (objectInputStream != null) {
			
			msg message = null;
        	//msg sendMsg = new msg("hello client");
        	
        	String str = null;
        	
        	try {
        		
        		str = (String) objectInputStream.readObject();
        		
        		
        		
        		Log.v("NITESH", str);
        		
        		
        	}
        	
        	catch(Exception e){
        		
        		
        	}
			
			
			
		}
		
//		try {
//			socket.close();
//			objectOutputStream.close();
//			objectInputStream.close();
//			socket = null;
//			objectInputStream = null;
//			objectOutputStream = null;
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		// TODO Auto-generated method stub
		return null;
	}

	protected void onProgressUpdate(Integer... progress) {
        
    }

    protected void onPostExecute(Long result) {
        
    }
	
	

}

